package middleware

import (
	"context"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strconv"
	"test-demo/api/internal/config"
	"test-demo/api/internal/types"
	"test-demo/common"
)

type AuthTokenMiddleware struct {
	config.Config
}

func NewAuthTokenMiddleware() *AuthTokenMiddleware {
	return &AuthTokenMiddleware{}
}

func (m *AuthTokenMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		conf.Load("etc/tobao.yaml", &m)
		token := r.Header.Get("token")
		userid, _ := strconv.Atoi(r.FormValue("userid"))
		res := common.AnalysisToken(m.AuthToken.AccessSecret, userid, token)
		if res != nil {
			httpx.OkJsonCtx(context.Background(), w, &types.Response{
				Code:    10001,
				Message: res.Error(),
				Data:    nil,
			})
			return
		}
		// Passthrough to next handler if need
		next(w, r)
	}
}
